<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-semibold text-gray-800">易耗品统计</h2>
      <div class="flex space-x-3">
        <select v-model="selectedPeriod" @change="loadStatistics" class="px-3 py-2 border border-gray-300 rounded-md shadow-sm text-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
          <option value="week">本周</option>
          <option value="month">本月</option>
          <option value="quarter">本季度</option>
          <option value="year">本年</option>
        </select>
        <button @click="exportStatistics" class="flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2">
          <DocumentArrowDownIcon class="h-5 w-5 mr-2" />
          导出统计
        </button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-blue-500 to-blue-600">
          <ChartBarIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.totalPlans }}</div>
          <div class="text-sm text-gray-500">计划总数</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-green-500 to-green-600">
          <CheckCircleIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.approvedPlans }}</div>
          <div class="text-sm text-gray-500">已批准计划</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-yellow-500 to-yellow-600">
          <ClockIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.pendingPlans }}</div>
          <div class="text-sm text-gray-500">待审批计划</div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6 flex items-center space-x-4">
        <div class="flex-shrink-0 w-16 h-16 rounded-full flex items-center justify-center text-white text-2xl bg-gradient-to-br from-purple-500 to-purple-600">
          <ShoppingBagIcon class="h-8 w-8" />
        </div>
        <div>
          <div class="text-3xl font-bold text-gray-900">{{ statistics.totalReceives }}</div>
          <div class="text-sm text-gray-500">领用记录</div>
        </div>
      </div>
    </div>

    <!-- 预算统计 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">预算统计</h3>
        <div class="space-y-4">
          <div class="flex justify-between items-center">
            <span class="text-gray-600">总预算</span>
            <span class="text-lg font-semibold text-blue-600">¥{{ formatNumber(statistics.totalBudget) }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">已使用</span>
            <span class="text-lg font-semibold text-green-600">¥{{ formatNumber(statistics.usedBudget) }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">剩余预算</span>
            <span class="text-lg font-semibold text-orange-600">¥{{ formatNumber(statistics.remainingBudget) }}</span>
          </div>
          <div class="w-full bg-gray-200 rounded-full h-2">
            <div class="bg-blue-600 h-2 rounded-full" :style="{ width: getBudgetUsagePercentage() + '%' }"></div>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">领用统计</h3>
        <div class="space-y-4">
          <div class="flex justify-between items-center">
            <span class="text-gray-600">计划内领用</span>
            <span class="text-lg font-semibold text-green-600">{{ statistics.plannedReceives }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">计划外领用</span>
            <span class="text-lg font-semibold text-orange-600">{{ statistics.unplannedReceives }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">总领用数量</span>
            <span class="text-lg font-semibold text-blue-600">{{ statistics.totalQuantity }}</span>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">计划状态</h3>
        <div class="space-y-4">
          <div class="flex justify-between items-center">
            <span class="text-gray-600">已批准</span>
            <span class="text-lg font-semibold text-green-600">{{ statistics.approvedPlans }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">待审批</span>
            <span class="text-lg font-semibold text-yellow-600">{{ statistics.pendingPlans }}</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-600">已拒绝</span>
            <span class="text-lg font-semibold text-red-600">{{ statistics.rejectedPlans }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">预算使用情况</h3>
        <div ref="budgetChart" class="h-64"></div>
      </div>

      <div class="bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">领用趋势</h3>
        <div ref="trendChart" class="h-64"></div>
      </div>
    </div>

    <!-- 详细统计表格 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">详细统计</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">实验室</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">计划数</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">领用数</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">总预算</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">已使用</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">使用率</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in detailedStats" :key="item.laboratory">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ item.laboratory }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.planCount }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ item.receiveCount }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ formatNumber(item.totalBudget) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">¥{{ formatNumber(item.usedAmount) }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="getUsageRateClass(item.usageRate)">
                  {{ item.usageRate }}%
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import * as echarts from 'echarts'
import VChart from 'vue-echarts'
import request from '@/utils/request'
import {
  ChartBarIcon,
  CheckCircleIcon,
  ClockIcon,
  ShoppingBagIcon,
  DocumentArrowDownIcon
} from '@heroicons/vue/24/outline'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  LineChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 响应式数据
const loading = ref(false)
const selectedPeriod = ref('month')
const statistics = ref({
  totalPlans: 0,
  approvedPlans: 0,
  pendingPlans: 0,
  rejectedPlans: 0,
  totalReceives: 0,
  plannedReceives: 0,
  unplannedReceives: 0,
  totalQuantity: 0,
  totalBudget: 0,
  usedBudget: 0,
  remainingBudget: 0
})

const detailedStats = ref([])

// 图表引用
const budgetChart = ref(null)
const trendChart = ref(null)

// 加载统计数据
const loadStatistics = async () => {
  try {
    loading.value = true
    
    // 加载统计数据
    const response = await request.get('/statistics/consumable')
    const data = response.data
    
    // 设置总体统计数据
    Object.assign(statistics.value, data)
    
    // 设置详细统计数据
    if (data.laboratoryConsumption) {
      detailedStats.value = data.laboratoryConsumption.map(item => ({
        laboratory: item.laboratoryName,
        planCount: item.planCount || 0,
        receiveCount: item.receiveCount || 0,
        totalBudget: item.totalBudget || 0,
        usedAmount: item.usedAmount || 0,
        usageRate: item.totalBudget && item.totalBudget > 0 
          ? Math.round((item.usedAmount / item.totalBudget) * 100) 
          : 0
      }))
    } else {
      detailedStats.value = []
    }
    
    // 数据加载完成后初始化图表
    await initCharts()
    
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 导出统计
const exportStatistics = async () => {
  try {
    const response = await request.get('/reports/consumable/export', {
      responseType: 'blob'
    })
    
    const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'consumable_statistics.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 格式化数字
const formatNumber = (num) => {
  if (!num) return '0'
  return num.toLocaleString()
}

// 获取预算使用百分比
const getBudgetUsagePercentage = () => {
  if (!statistics.value.totalBudget || statistics.value.totalBudget === 0) return 0
  return Math.round((statistics.value.usedBudget / statistics.value.totalBudget) * 100)
}

// 获取使用率样式类
const getUsageRateClass = (rate) => {
  if (rate >= 80) return 'bg-red-100 text-red-800'
  if (rate >= 60) return 'bg-yellow-100 text-yellow-800'
  return 'bg-green-100 text-green-800'
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 预算使用情况饼图
  if (budgetChart.value) {
    const budgetOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '预算使用',
          type: 'pie',
          radius: '50%',
          data: [
            { value: statistics.value.usedBudget, name: '已使用' },
            { value: statistics.value.remainingBudget, name: '剩余预算' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    const budgetChartInstance = echarts.init(budgetChart.value)
    budgetChartInstance.setOption(budgetOption)
  }
  
  // 领用趋势折线图
  if (trendChart.value) {
    const trendOption = {
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '领用数量',
          type: 'line',
          data: [120, 132, 101, 134, 90, 230],
          smooth: true
        }
      ]
    }
    
    const trendChartInstance = echarts.init(trendChart.value)
    trendChartInstance.setOption(trendOption)
  }
}

// 组件挂载
onMounted(() => {
  loadStatistics()
})
</script>
